import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/x3_form_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

class AdvancedFilterFuzzySearchScreen extends StatefulWidget {
  ///模糊搜索api
  final String inputApi;

  ///已选子项
  final List<BaseKeyValueModel> selectList;

  ///子项唯一key
  final String childOnlyKey;

  ///子项唯一value
  final String childOnlyValue;

  final String childSearchKey;

  ///完成事件
  final Function(List<BaseKeyValueModel> item) completeEvent;

  ///子项Widget
  final Widget Function(Map<String, dynamic> item, bool isSelect) childWidget;

  ///是多选
  final bool isMultipleChoice;

  final String hintText;

  final BaseHttpMethodEnum method;

  /// 参数
  final Map<String, dynamic> params;

  /// 不需要搜索框
  final bool notNeedSearch;

  /// 当前是否分页
  final bool isPaging;

  const AdvancedFilterFuzzySearchScreen({
    Key key,
    @required this.inputApi,
    @required this.selectList,
    @required this.childOnlyKey,
    @required this.childOnlyValue,
    @required this.completeEvent,
    @required this.childWidget,
    @required this.hintText,
    this.childSearchKey = 'searchKey',
    this.isMultipleChoice = false,
    this.method = BaseHttpMethodEnum.POST,
    this.params,
    this.notNeedSearch = false,
    this.isPaging = true,
  }) : super(key: key);

  @override
  _AdvancedFilterFuzzySearchScreenState createState() => _AdvancedFilterFuzzySearchScreenState();
}

class _AdvancedFilterFuzzySearchScreenState extends State<AdvancedFilterFuzzySearchScreen> {
  List<BaseKeyValueModel> _selectList = [];
  BaseRefreshController _controller = BaseRefreshController();

  @override
  void initState() {
    super.initState();

    ///初始化数据
    _selectList.clear();
    if (widget.isMultipleChoice) {
      _selectList.addAll([...widget.selectList]);
    } else {
      if (widget.selectList.length == 1 || widget.selectList.length != 0) {
        _selectList.add(widget.selectList[0]);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (!widget.notNeedSearch) _buildSearchFilter(),
        if (!widget.notNeedSearch) SizedBox(height: 8),
        Expanded(child: _buildListView()),
        _buildFooterWidget(),
      ],
    );
  }

  Widget _buildSearchFilter() {
    return Container(
      height: 40,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8), border: Border.all(color: Color(0xFFDFDFDF), width: 1)),
      padding: EdgeInsets.all(2),
      child: BaseSearchFilterComponent(
        hintText: widget.hintText,
        onEditingComplete: (String value) {
          this._controller.refresh(params: {widget.childSearchKey: value});
        },
        showScanIcon: false,
        onClearOut: () {
          this._controller.refresh(params: {widget.childSearchKey: ""});
        },
      ),
    );
  }

  Widget _buildListView() {
    return BaseRefreshComponent(
      path: widget.inputApi,
      method: widget.method,
      params: widget.params == null ? {widget.childSearchKey: ""} : {...widget.params, widget.childSearchKey: ""},
      buildItem: _buildListViewItem,
      isPaging: widget.isPaging,
      controller: _controller,
    );
  }

  Widget _buildListViewItem(Map<String, dynamic> item, int index) {
    String itemOnlyKey = BaseUtils.getKeyData(item, widget.childOnlyKey).toString();
    int _isSelectIndex = _selectList.indexWhere((element) => element.key == itemOnlyKey);
    return InkWell(
      onTap: () => _itemOnTapEvent(item, _isSelectIndex != -1),
      child: widget.childWidget(item, _isSelectIndex != -1),
    );
  }

  Widget _buildFooterWidget() {
    if (widget.isMultipleChoice) {
      return _buildMultipleChoiceFooterWidget();
    }
    return Container();
  }

  Widget _buildMultipleChoiceFooterWidget() {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          Expanded(child: BaseButton(text: '取消', onPress: _closeFuzzySearchScreen, fill: false, height: 40)),
          SizedBox(width: 8.0),
          Expanded(child: BaseButton(text: '确定', onPress: _completeEvent, fill: false, height: 40)),
        ],
      ),
    );
  }

  void _itemOnTapEvent(Map<String, dynamic> item, bool isSelect) {
    String itemOnlyKey = BaseUtils.getKeyData(item, widget.childOnlyKey).toString();
    String itemOnlyValue = BaseUtils.getKeyData(item, widget.childOnlyValue).toString();
    if (isSelect) {
      int _index = _selectList.indexWhere((element) => element.key == itemOnlyKey);
      if (_index != -1) {
        _selectList.removeAt(_index);
      }
    } else {
      if (widget.isMultipleChoice) {
        _selectList.add(BaseKeyValueModel(key: itemOnlyKey, value: itemOnlyValue));
      } else {
        if (_selectList.isNotEmpty) {
          _selectList.clear();
        }
        _selectList.add(BaseKeyValueModel(key: itemOnlyKey, value: itemOnlyValue));
        _completeEvent();
      }
    }
    setState(() {});
  }

  void _completeEvent() {
    widget.completeEvent([..._selectList]);
    BaseRouterUtil.getInstance().pop();
  }

  void _closeFuzzySearchScreen() {
    BaseRouterUtil.getInstance().pop();
  }
}
